<?php

namespace app\openapi\controller;

use Exception;
use app\common\services\WXMsgCrypt;
use app\common\services\QianFan as QianFanServices;
use Gaarf\XmlToPhp\Convertor;
use think\facade\Cache;
use think\facade\Log;
use think\response\Xml;

class Recover extends Base
{
    /**
     * 外部消息回调
     */
    public function notify()
    {
        if (request()->isGet()) {
            $param = $this->request->param();
            $wxcpt = new WXMsgCrypt();
            // 需要返回的明文
            if (!empty($param['echostr'])) {
                $echostr = $wxcpt->VerifyURL($param['signature'], $param['timestamp'], $param['nonce'], $param['echostr']);
                echo ($echostr);
                exit;
            }
        } else {
            $xml = file_get_contents("php://input");
            $param = $this->request->param();

            $wxcpt = new WXMsgCrypt();
            $xml_data = $wxcpt->DecryptMsg($param['msg_signature'], $param['timestamp'], $param['nonce'], $xml);
            $msg_data = Convertor::covertToArray($xml_data);

            $user_open_id = $msg_data['FromUserName'];

            $data = [
                'user_id' => $user_open_id,
                'disable_search' => false,
                'enable_citation' => false,
                'messages' => [],
            ];

            $messages = [];
            $cache_str = "chat:" . $user_open_id;
            if (Cache::has($cache_str)) {
                $messages = Cache::get($cache_str);
                if (count($messages) ^ 1 === 0) {
                    $messages = [];
                }
            }
            $messages[] = [
                "role" => "user",
                "content" => $msg_data['Content'],
            ];
            $data['messages'] = $messages;
            $chat = new QianFanServices();
            $result = $chat->chat($data);
            $result_msg = $result['result'];

            $messages[] = [
                "role" => "assistant",
                "content" => $result_msg,
            ];

            Cache::set($cache_str, $messages);

            $res = [
                'ToUserName' => $msg_data['FromUserName'],
                'FromUserName' => $msg_data['ToUserName'],
                'CreateTime' => time(),
                'MsgType' => 'text',
                'Content' => $result_msg,
            ];
            return xml($res, 200, [], ['root_node' => 'xml']);
        }
    }
}
